package com.byzk.p2p.app.controller;

import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.byzk.p2p.admin.bank.dto.BankCard;
import com.byzk.p2p.admin.bank.service.BankCardService;
import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.fuiou.config.Config;
import com.byzk.p2p.admin.fuiou.dto.RegisterDto;
import com.byzk.p2p.admin.fuiou.util.SecurityUtils;
import com.byzk.p2p.admin.fuiou.util.WebUtils;
import com.byzk.p2p.admin.fuiou.util.XmlUtils;
import com.byzk.p2p.admin.money.service.FundRecordService;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.system.dto.Callback;
import com.byzk.p2p.admin.system.dto.SystemConfig;
import com.byzk.p2p.admin.system.service.CallbackService;
import com.byzk.p2p.admin.system.service.SystemService;
import com.byzk.p2p.admin.user.dto.InviteRef;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.dto.UserAuth;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserAuthService;
import com.byzk.p2p.admin.user.service.UserService;
import com.byzk.p2p.front.service.FrontUserService;


@Controller
@RequestMapping("/app/fuion")
@Scope("prototype")
public class AppHfController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private FrontUserService frontUserService;
	@Autowired
	private UserAccountService accountService;
	@Autowired
	private UserAuthService authService;
	@Autowired
	private BankCardService bankService;
	@Autowired
	private CallbackService callbackService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private FundRecordService fundService;
	
	/**
	 * 检查是否具备操作条件(是否开户)
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/check")
	public String authCheck(@RequestParam("uid") Integer uid) throws Exception{
		User dto=userService.getById(uid);
		if("N".equals(dto.getFuionAccount())){
			super.printJSON(new JsonMsg(1, "该用户还未开户"));
			return null;
		}
		super.printJSON(new JsonMsg(-1, "操作成功"));
		return null;
	}
	
	@RequestMapping("/register")
	public String register(@RequestParam("userId") Integer userId) throws Exception {
		try {
			User user=userService.getById(userId);
			UserAuth auth=authService.getAuthByUidAndType(userId, "id5");
			List<BankCard> cardList=bankService.listCardByUserId(userId);
			RegisterDto dto=new RegisterDto();
			
			dto.setBank_nm(cardList.get(0).getBankName());
			dto.setCapAcntNm("");
			dto.setCapAcntNo(cardList.get(0).getCardNo());
			dto.setCertif_id(auth.getAuthName());
			dto.setCity_id(cardList.get(0).getCityCode());
			dto.setCust_nm(user.getRealname());
			dto.setEmail("");
			dto.setPassword(user.getDealPassword());
			dto.setLpassword(user.getLoginPassword());
			dto.setMchnt_cd(Config.mchnt_cd);
			dto.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));
			dto.setMobile_no(user.getPhone());
			dto.setParent_bank_id(cardList.get(0).getBankName());
			dto.setRem("");
			String inputStr=dto.regSignVal();
			dto.setSignature(SecurityUtils.sign(inputStr));
			//http请求富友开户接口并获取返回数据
			String backStr;
		
			backStr = WebUtils.sendHttp(Config.reg_url,dto);

			System.out.println(backStr);
			
			Callback callback=new Callback("开户",backStr,new Date());
			callbackService.saveOrUpdate(callback);
			
			String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
			String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
			if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
				/**
				 * 开户奖励
				 */
				SystemConfig config=systemService.listSystemConfig();
				UserAccount account=accountService.getByUserId(user.getId());
	
				/** 开户成功之后，同步平台账户和金账户金额数据**/
				Double balance=account.getBalance();
				if(balance>0){
					//同步平台账户和金账户金额数据
					String code = accountService.updateBalance(account.getUserId(), balance);
					if("0000".equals(code)){
						//开通托管账户奖励::上线得到邀请奖励,本人得到开通托管账户奖励
						setInviteMoney(user, config, account);						
					}					
				}else{
					//开通托管账户奖励::上线得到邀请奖励,本人得到开通托管账户奖励
					setInviteMoney(user, config, account);						
				}

			}
			else{
				super.printJSON(new JsonMsg(1, "开户失败",resp_code));
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			super.printJSON(new JsonMsg(2, "开户失败","系统数据异常"));
			return null;
		}
		
	}
	
	/**
	 * 开通托管账户奖励::上线得到邀请奖励,本人得到开通托管账户奖励
	 * @param user
	 * @param config
	 * @param account
	 * @throws Exception
	 */
	private void setInviteMoney(User user, SystemConfig config, UserAccount account) throws Exception {
		user.setFuionAccount("Y");
		userService.saveOrUpdate(user);

		account.setStayAmount(account.getStayAmount()+config.getRegReward());
		accountService.saveOrUpdate(account);
		
		/** 为邀请人添加奖励 **/
		InviteRef inviteRef = userService.getInviteRefByUserId(user.getId());
		if(inviteRef != null){
			int inviteCount = frontUserService.inviteCountToPid(inviteRef.getPid());
			Double inviteMoney =  0.0;
			if(inviteCount < 20) {
				inviteMoney = config.getInviteReward();
			}else if(inviteCount >= 20 && inviteCount < 50) {
				inviteMoney = 100.00;
			}else if(inviteCount >= 50) {
				inviteMoney = 200.00;
			}
			UserAccount inviteAccount = accountService.getByUserId(inviteRef.getPid());
			inviteAccount.setStayAmount(inviteAccount.getStayAmount()+inviteMoney);
			accountService.saveOrUpdate(inviteAccount);
			//上线得到邀请奖励
			fundService.addFundRecord(inviteAccount.getUserId(), inviteMoney, 0.0, "PC", "邀请奖励", FundRecordType.Type.STAY_MONEY.index, 0.0);
		}
		//本人得到开通托管账户奖励
		fundService.addFundRecord(user.getId(), config.getRegReward(), 0.0, "PC", "开通托管账户奖励", FundRecordType.Type.STAY_MONEY.index, 0.0);
		session.setAttribute("_user", user);
		super.printJSON(new JsonMsg(-1, "开户成功"));
	}
}
